import { createSlice } from "@reduxjs/toolkit";
import http from "../../utils/http";
import { setToken as _setToken, getToken, clearToken } from "../../utils/token";
import { message } from "antd";
import { loginAPI, getProfileAPI } from "../../apis/user";

const userStore = createSlice({
  name: "user",
  initialState: {
    token: getToken() || "",
    userInfo: {},
  },
  reducers: {
    setToken(state, action) {
      state.token = action.payload;
      // localStorage.setItem('token_key', action.payload)
      _setToken(action.payload);
    },
    setUserInfo(state, action) {
      state.userInfo = action.payload;
    },
    clearUserInfo(state) {
      state.token = "";
      state.userInfo = "";
      clearToken();
    },
  },
});

const { setToken, setUserInfo, clearUserInfo } = userStore.actions;

const userReducer = userStore.reducer;

// 异步方法，登录获取token
const fetchToken = (loginForm) => {
  return async (dispatch) => {
    const res = await loginAPI(loginForm);
    // const res = await http.post('/user/login', loginForm)
    // 提交同步action进行token保存
    dispatch(setToken(res.data.token));
  };
};

// 异步方法，获取用户个人信息
const fetchUserInfo = () => {
  return async (dispatch) => {
    try {
      const res = await getProfileAPI();
      // console.log(res)
      dispatch(setUserInfo(res.data));
    } catch (error) {
      message.error('登录信息失效，请重新登录')
    }
  };
};

export { setToken, fetchToken, fetchUserInfo, clearUserInfo };

export default userReducer;
